using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using LCL.Config;
using LCL.IBuilder;
using LCL.LData;
using LCL.Tools.WinFrm;

namespace LCL.Tools {
    public class UIFactory {
        private UIFactory() {

        }
        public static string Title = "程序开发辅助工具";
        public static IUIHelp UIFact() {
            return new UIHelp();
        }

        public static IDbObject UIDb() {
            return Utility.GetDbo();
        }

        public static DialogResult ShowThreadExceptionDialog(Exception ex) {
            string errorMessage = "错误信息：\n\n"+
                ex.Message+"\n\n"+ex.GetType()+
                "\n\nStack Trace:\n"+
                ex.StackTrace;
            LCL.WinControls.SendErrInfo infoform = new LCL.WinControls.SendErrInfo(Title+"LCL.Tools",errorMessage);
            return infoform.ShowDialog();
        }
        //显示遮罩层窗体
        public static void ShowProcessing(string msg,Form owner,ParameterizedThreadStart work,object workArg = null) {
            SplashScreen processingForm = new SplashScreen(msg);
            dynamic expObj = new ExpandoObject();
            expObj.Form=processingForm;
            expObj.WorkArg=workArg;
            processingForm.SetWorkAction(work,expObj);
            processingForm.ShowDialog(owner);
            if(processingForm.WorkException!=null) {
                throw processingForm.WorkException;
            }
        }
    }
    /// <summary>
    /// UI接口
    /// </summary>
    public interface IUIHelp {
        /// <summary>
        /// 绑定数据库到ComboBox控件
        /// </summary>
        /// <param name="cmbDB"></param>
        void BindDataBaseList(ComboBox cmbDB);
        /// <summary>
        /// 绑定数据库到ComboBox控件
        /// </summary>
        /// <param name="cmbDB"></param>
        void BindDataBaseList(ToolStripComboBox cmbDB);

        /// <summary>
        /// 绑定生成引擎到ComboBox控件
        /// </summary>
        /// <param name="cmbEng"></param>
        void BindBuilderEngineList(ComboBox cmbEng);
        /// <summary>
        /// 绑定表信息到DataGridView控件
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="tableName"></param>
        void BinTableInfo(DataGridView dgv);
        /// <summary>
        /// 绑定表关系到DataGridView控件
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="tableName"></param>
        void BinTableRelation(DataGridView dgv);
        /// <summary>
        /// 绑定模板达到树形控件
        /// </summary>
        /// <param name="tv"></param>
        void BinTemplateTree(TreeView tv);
        /// <summary>
        /// 根据Excel更新字段描述
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        bool UpdateColumns(string filePath);
        /// <summary>
        /// 根据字段描述
        /// </summary>
        /// <param name="table"></param>
        void UpdateColumnRemark(string tableName);
    }
    public class UIHelp:IUIHelp {
        public IDbObject idb = null;
        public UIHelp() {
            idb=Utility.GetDbo();
        }
        /// <summary>
        /// 数据库列表
        /// </summary>
        /// <param name="cmbDB"></param>
        /// <returns></returns>
        public void BindDataBaseList(ComboBox cmbDB) {
            List<DataBaseModel> dbmList = idb.GetDBList(DbConfig.GetConfig().DbHost);
            foreach(DataBaseModel dbm in dbmList) {
                string item = dbm.DatabaseName;
                cmbDB.Items.Add(item);
                if(AppConfig.GetInstance().DbName.Equals(item)) {
                    cmbDB.SelectedItem=item;
                }
            }
        }
        public void BindDataBaseList(ToolStripComboBox cmbDB) {
            List<DataBaseModel> dbmList = idb.GetDBList(DbConfig.GetConfig().DbHost);
            foreach(DataBaseModel dbm in dbmList) {
                string item = dbm.DatabaseName;
                cmbDB.Items.Add(item);
                if(AppConfig.GetInstance().DbName.Equals(item)) {
                    cmbDB.SelectedItem=item;
                }
            }
        }
        public void BindBuilderEngineList(ComboBox cmbEng) {
            var builder = new BuilderFactory();
            var _builderDescriptorList = builder.GetBuilderAll();
            foreach(var item in _builderDescriptorList) {
                LParam param = LParam.Create(item.Name,item);
                cmbEng.Items.Add(param);
            }
        }
        public void BinTableInfo(DataGridView dgv) {
            var list = idb.GetColumnInfoList(AppConfig.GetInstance().DbName,AppConfig.GetInstance().DbTableName);
            dgv.DataSource=list;
        }
        public void BinTableRelation(DataGridView dgv) {
            var dt = idb.GetTableRelation(AppConfig.GetInstance().DbTableName);
            dgv.DataSource=dt;
        }
        public bool UpdateColumns(string filePath) {
            DataTable distinct = MyXlsHelper.GetData(filePath).Tables[0];
            if(distinct==null) return false;
            if(distinct.Columns.Contains("字段名称")&&distinct.Columns.Contains("字段说明")) {
                return true;
            } else {
                return false;
            }
        }
        public void BinTemplateTree(TreeView tv) {
            string templatefolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"Template\\TemplateFile");
            tv.Nodes.Clear();
            TempNode tempNode = new TempNode("代码模板");
            tempNode.NodeType="root";
            tempNode.FilePath=templatefolder;
            tempNode.ImageIndex=3;
            tempNode.SelectedImageIndex=4;
            tempNode.Expand();
            tv.Nodes.Add(tempNode);
            LoadFolderTree(tempNode,templatefolder);
        }
        private void LoadFolderTree(TreeNode parentnode,string templateFolder) {
            DirectoryInfo directoryInfo = new DirectoryInfo(templateFolder);
            if(!directoryInfo.Exists) return;
            DirectoryInfo[] directories = directoryInfo.GetDirectories().OrderBy(p => p.Name).ToArray();
            for(int i = 0;i<directories.Length;i++) {
                TempNode tempNode = new TempNode(directories[i].Name);
                tempNode.NodeType="folder";
                tempNode.FilePath=directories[i].FullName;
                tempNode.ImageIndex=3;
                tempNode.SelectedImageIndex=4;
                parentnode.Nodes.Add(tempNode);
                this.LoadFolderTree(tempNode,directories[i].FullName);
            }
            FileInfo[] files = directoryInfo.GetFiles().OrderBy(p => p.Name).ToArray();
            int num = files.Length;
            for(int j = 0;j<num;j++) {
                if(files[j].Extension==".tt"||files[j].Extension==".cmt"||
                    files[j].Extension==".aspx"||files[j].Extension==".cs") {
                    TempNode tempNode2 = new TempNode(files[j].Name);
                    tempNode2.FilePath=files[j].FullName;
                    string extension = files[j].Extension;
                    switch(extension) {
                        case ".tt":
                            tempNode2.NodeType="tt";
                            tempNode2.ImageIndex=2;
                            tempNode2.SelectedImageIndex=2;
                            break;
                        case ".cmt":
                            tempNode2.NodeType="cmt";
                            tempNode2.ImageIndex=2;
                            tempNode2.SelectedImageIndex=2;
                            break;
                        case ".aspx":
                            tempNode2.NodeType="aspx";
                            tempNode2.ImageIndex=2;
                            tempNode2.SelectedImageIndex=2;
                            break;
                        case ".cs":
                            tempNode2.NodeType="aspx";
                            tempNode2.ImageIndex=2;
                            tempNode2.SelectedImageIndex=2;
                            break;
                        default:
                            break;
                    }
                    parentnode.Nodes.Add(tempNode2);
                }
            }
        }
        public void UpdateColumnRemark(string tableName) {
            var colist = idb.GetColumnInfoList(AppConfig.GetInstance().DbName,tableName);
            BaiduTranslator trans = new BaiduTranslator("20170602000050688","l_A95b8C07KdwIe9ILtR");
            foreach(var item in colist) {
                if(string.IsNullOrWhiteSpace(item.Description)) {
                    string remark = "";
                    string[] strarr = item.ColumnName.Split(new char[] { '_' });
                    if(strarr.Length>1) {
                        string trn = "";
                        for(int i = 0;i<strarr.Length;i++) {
                            string temp = DatatypeMapEx.Translator(strarr[i]);
                            if(string.IsNullOrWhiteSpace(temp)) {
                                trn+=trans.Translate(strarr[i],"en","zh");
                            } else {
                                trn+=temp;
                            }
                        }
                        remark=trn;
                    } else {
                        remark=DatatypeMapEx.Translator(item.ColumnName);
                        if(string.IsNullOrWhiteSpace(remark)) {
                            remark=trans.Translate(item.ColumnName,"en","zh");
                        }
                    }
                    item.Description=remark;
                    if(!string.IsNullOrWhiteSpace(item.Description)) {
                        idb.ExtendedProperty(false,item.Description,tableName,item.ColumnName);
                    }
                }
            }
        }
    }
}
